﻿using System;
using System.ComponentModel.Design;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Task = System.Threading.Tasks.Task;

namespace Agile.VSIX {
    /// <summary>
    /// 搜索代码
    /// </summary>
    internal sealed class CodeSearchCommand {
        /// <summary>
        /// Command ID.
        /// </summary>
        public const int CommandId = 4131;

        /// <summary>
        /// Command menu group (command set GUID).
        /// </summary>
        public static readonly Guid CommandSet = new Guid("1c21120b-12b7-4d3a-ab61-1962f6426c0c");

        /// <summary>
        /// VS Package that provides this command, not null.
        /// </summary>
        private readonly AsyncPackage package;

        /// <summary>
        /// Initializes a new instance of the <see cref="CodeSearchCommand"/> class.
        /// Adds our command handlers for menu (commands must exist in the command table file)
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        /// <param name="commandService">Command service to add command to, not null.</param>
        private CodeSearchCommand(AsyncPackage package,OleMenuCommandService commandService) {
            this.package = package ?? throw new ArgumentNullException(nameof(package));
            commandService = commandService ?? throw new ArgumentNullException(nameof(commandService));

            var menuCommandID = new CommandID(CommandSet,CommandId);
            var menuItem = new MenuCommand(this.Execute,menuCommandID);
            commandService.AddCommand(menuItem);
        }

        /// <summary>
        /// Gets the instance of the command.
        /// </summary>
        public static CodeSearchCommand Instance {
            get;
            private set;
        }

        /// <summary>
        /// Gets the service provider from the owner package.
        /// </summary>
        private Microsoft.VisualStudio.Shell.IAsyncServiceProvider ServiceProvider {
            get {
                return this.package;
            }
        }

        /// <summary>
        /// Initializes the singleton instance of the command.
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        public static async Task InitializeAsync(AsyncPackage package) {
            // Switch to the main thread - the call to AddCommand in CodeSearchCommand's constructor requires
            // the UI thread.
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(package.DisposalToken);

            OleMenuCommandService commandService = await package.GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;
            Instance = new CodeSearchCommand(package,commandService);
        }

        private void Execute(object sender,EventArgs e) {
            ThreadHelper.ThrowIfNotOnUIThread();
            DTE dte = ServiceProvider.GetServiceAsync(typeof(DTE)).Result as DTE;
            CodeSearchExecute(dte);
        }
        /// <summary>
        /// 搜索代码
        /// </summary>
        private void CodeSearchExecute(DTE dte) {
            ThreadHelper.ThrowIfNotOnUIThread();
            try {
                if(dte.ActiveDocument != null) {
                    var selection = (TextSelection)dte.ActiveDocument.Selection;
                    if(selection != null) {
                        var encodedSelection = selection.Text;
                        if(!string.IsNullOrWhiteSpace(selection.Text)) {
                            System.Diagnostics.Process.Start(string.Format("https://www.baidu.com/s?wd={0}",encodedSelection));
                            System.Diagnostics.Process.Start(string.Format("https://search.gitee.com/?skin=rec&type=code&q={0}",encodedSelection));
                            System.Diagnostics.Process.Start(string.Format("https://github.com/search?q={0}&type=code",encodedSelection));
                            System.Diagnostics.Process.Start(string.Format("http://www.bing.com/search?q={0}",encodedSelection));
                            System.Diagnostics.Process.Start(string.Format("https://www.so.com/s?ie=utf-8&src=360se7_addr&q={0}",encodedSelection));
                        }
                        OutputWindowHelper.DiagnosticWriteLine("搜索" + encodedSelection + "");
                    } else {
                        OutputWindowHelper.WarningWriteLine("请选择活动文档！");
                    }
                } else {
                    OutputWindowHelper.WarningWriteLine("没有打开文档！");
                }
            } catch(Exception ex) {
                OutputWindowHelper.ExceptionWriteLine(string.Format(CultureInfo.CurrentCulture,ex.Message),ex);
            }
        }
    }
}
